import md5 from '@/utils/md5.js'
import { reactive,getCurrentInstance,defineEmits } from 'vue'
import type { FormInstance,FormRules } from 'element-plus'
import { throwError } from 'element-plus/es/utils/error.mjs'

const nuxtApp:any=useNuxtApp()

interface LoginFormClass{
  mobile:string,
  password:string,
  imgCode:string,
  imgCodeToken:string,
}

interface RegFormClass{
  mobile:string,
  nickName:string,
  password:string
}

interface ForgetFormClass{
  mobile:string,
  shortMessageCode:string,
  passwordOriginal:string,
  passwordConfirm:string
}

export default function useMethods(t:any,params:any,router:any) {
  // console.log("传递入参：",params)
  const { proxy }:any = getCurrentInstance()

  

  let localUser= {} //localCache.getCache('user')
  //注意，如果使用store，在export default中申明store，不要在外部直接const，否则找不到store
  // const store=useStore()
  

  let codeToken=''
  function resetData(form:FormInstance | undefined){
    if(!form) return
    form.resetFields()
   }
   
   const submitData=async (form:FormInstance | undefined,formName:string)=>{
     if (!form) return
     await form.validate((valid,fields)=>{
      //  console.log("formName: ",formName)
      //  console.log("valid: ",valid)
      //  console.log("fields: ",fields)
       
       if(valid){
         if(formName=='login'){
          //  console.log("登录-请求提交",params.loginForm.mobile)
           login(params.loginForm)
         }else if(formName=='register'){
          //  console.log("一键注册-请求提交",params.regForm.value)
           register(params.regForm)
         }else if(formName=='forget'){
          //  console.log("忘记密码-请求提交",params.forgetForm.value)
           forget(params.forgetForm)
         }
         
       }
     })
   }

   const login=async(params:LoginFormClass)=>{
    
    let reqData={...params}
    //如果密码从缓存中取出，则不需要二次加密
    // console.log("localUser: ",localUser)
    //1加密密码
    reqData.password=md5.hex_md5(reqData.password+md5.KEY)
    reqData.imgCodeToken=codeToken
    // console.log("codeToken---------",codeToken)
    // console.log("加密的密码：",reqData)

    const {data,error,status}=await LoginByPwd({
      body:JSON.stringify(reqData),
      method:'POST',
      lazy:true})
    console.log("登录响应：",data.value.responseMsg)
    console.log("error: ",error)
    console.log("status: ",status)
    if(process.server && error.value){
      throwError((error.value?.data,error.value?.data.error+': '+error.value?.data.status),'页面加载失败，请联系客服！')

    }

    if(data.value){
      if(!data.value.responseMsg){
        nuxtApp.$message('success','登录成功')
        localUser=data.value
        //如果在这里需要改变父级vue的参数，使用proxy代理
        proxy.$emit('closeLogin',localUser)
        // console.log("localUser: ",localUser)
      }else{
        nuxtApp.$message('error',data.value.responseMsg)
      }
      
    }
    
  }
  
  function register(params:RegFormClass){
    let reqData={...params}
    reqData.password=md5.hex_md5('c123456'+md5.KEY)
    // proxy.$loading()
    // api.oneRegister(reqData).then((res:any)=>{
    //   if(res.success){
    //     // localCache.setCache('user',res.responseData)
    //     proxy.$message.success('恭喜您，注册会员成功！稍后将有专业客户经理为您服务！')
    //     // activeNav.value='login'
    //     // params.mobile=reqData.mobile
    //     store.commit('setRegiter',reqData.mobile)
        
    //     // proxy.$message.alert('恭喜您，注册会员成功！稍后将有专业客户经理为您服务！', 'Title', {
    //     //   // if you want to disable its autofocus
    //     //   // autofocus: false,
    //     //   confirmButtonText: 'OK',
    //     //   callback: (action: Action) => {
    //     //     console.log("---action: ",action)
    //     //   }
    //     // })
    //     //跳转首页
    //     // proxy.$router.push('/')
    //   }else{
    //     proxy.$message.error(res.responseMsg)
        
    //   }
    //   proxy.$loading().close()
    // })
  }

  function forget(params:ForgetFormClass){
    let reqData=params
    // api.forgetPassword(reqData).then((res:any)=>{
    //   if(res.success){
    //     // localCache.setCache('user',res.responseData)
    //     proxy.$message.success('恭喜您，修改密码成功！')
    //     // activeNav.value='login'
    //     params.mobile=reqData.mobile

    //     //跳转首页
    //     // proxy.$router.push('/')
    //   }else{
    //     proxy.$message.error(res.responseMsg)
        
    //   }
    // })
  }
  
  //动态变量获取
  let dyCode=t(`login['${nuxtApp.$getCodeParams(8)}Btn']`)
  
  function getCodeToken(){
    codeToken=nuxtApp.$getCodeParams(8)
    // console.log("更新codeToken：",codeToken)
    return codeToken
  }

  return {
    resetData,
    submitData,
    login,
    register,
    getCodeToken
  }
}




